package com.swift.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;

import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

public final class SysUtils {
	public static int getHasCode(int...args){
		StringBuilder result =  new StringBuilder();
		for (int i : args) {
			result.append(Integer.toString(i));
			result.append("-");
		}
		return result.toString().hashCode();
	}
	
	public static String secondToTime(int time) {  
        String timeStr = null;  
        int hour = 0;  
        int minute = 0;  
        int second = 0;  
        if (time <= 0)  
            return "00:00";  
        else {  
            minute = time / 60;  
            if (minute < 60) {  
                second = time % 60;  
                timeStr = unitFormat(minute) + ":" + unitFormat(second);  
            } else {  
                hour = minute / 60;  
                if (hour > 99)  
                    return "99:59:59";  
                minute = minute % 60;  
                second = time - hour * 3600 - minute * 60;  
                timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);  
            }  
        }  
        return timeStr;  
    }  
  
    public static String unitFormat(int i) {  
        String retStr = null;  
        if (i >= 0 && i < 10)  
            retStr = "0" + Integer.toString(i);  
        else  
            retStr = "" + i;  
        return retStr;  
    }  
    
    public static List<String> stringToList(String value, String separator){
		List<String> result = new ArrayList<String>();
		if (value != null && !value.isEmpty()){
			String[]  list = value.split(separator);
			if (list.length > 0){
				for(int i=0; i<list.length;i++){
					result.add(list[i]);
				}
			}
		}
		return result;
    }

    /*时间格式=》总秒数*/
	public static int timeToSecond(String value) {
		int result = 0;
		if (value != null){
			String[] timeStrings = value.split(":");
			int length = timeStrings.length;
			if (length > 0){
				for(int index=length-1; index>=0; index--){
					result+= Integer.parseInt(timeStrings[index])*Math.pow(60, (length-1-index));
				}
			}
		}
		return result;
	}
	
	public static void setFieldValue(Object object, String key, Object val){
		try {
			if (object != null){
				Field field = object.getClass().getDeclaredField(key);
				if (field != null){
					field.setAccessible(true);
					field.set(object, val);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
		
	public static String timeStamp2DateTime(int  timeSeconds, String format){
		if (timeSeconds == 0){
			return "";
		}
		Long timestamp =  (long)timeSeconds*1000;
		SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.getDefault());
		return dateFormat.format(new Date(timestamp));
	}
	
	public static String timeStamp2DateTime(int  timeSeconds){
		return timeStamp2DateTime(timeSeconds,  "yyyy年MM月dd日HH时mm分ss秒");
	}
	
	public static String timeStamp2MonthDayTime(int  timeSeconds){
		return timeStamp2DateTime(timeSeconds,  "MM月dd日HH时mm分");
	}
	
	public static String timeStamp2Date(int  timeSeconds){
		return timeStamp2DateTime(timeSeconds,  "yyyy年MM月dd日");
	}
	
	public static int date2TimeStamp(String dateString){
		int result = 0;
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
		try {
			Date date = dateFormat.parse(dateString);
			result = (int) (date.getTime() / 1000);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	public static Calendar timeStamp2Calendar(int timeStamp){
		Long timestamp =  (long)timeStamp*1000;
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(timestamp);
		return calendar;
	}
	
	public static int parseInt(String value){
		if (value != null && TextUtils.isDigitsOnly(value)){
			return Integer.parseInt(value);
		}
		return 0;
	}
	
	public static float parseFloat(String value){
		  if (!TextUtils.isEmpty(value)){
			  String floatString = value.replace(".", "");
			  if (TextUtils.isDigitsOnly(floatString)){
				  return Float.parseFloat(value);
			  }
		  }
		  return 0;
	}
	
	public static int getCurrentMonth() {
		 return Calendar.getInstance().get(Calendar.MONTH) + 1;
	}
	
	public static int getCurrentYear() {
		 return Calendar.getInstance().get(Calendar.YEAR); 
	}
	
	public static int getCurrentYearMonth() {
		return Calendar.getInstance().get(Calendar.MONTH) + 1;		 
	}
	
	
	public static <E> String join(List<E> list, String splitchar){
		StringBuilder sb = new StringBuilder();
		for (E e : list) {
			sb.append(e.toString() + splitchar);
		}
		String result = sb.toString();
		return result.substring(0, result.length() - 1);
	}
	
	public static void toggleView(View view){
		 if (view.getVisibility() == View.VISIBLE){
			 view.setVisibility(View.GONE);
		 }else{
			 view.setVisibility(View.VISIBLE);
		 }
	}
	
	public static boolean isAppOnForeground(Context context) {  
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);  
        String packageName = context.getPackageName();  

        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();  
        if (appProcesses == null)  
                return false;  

        for (RunningAppProcessInfo appProcess : appProcesses) {   
                if (appProcess.processName.equals(packageName)  && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {  
                        return true;  
                }  
        }  

        return false;  
	}
	
	public static String getHttpGetResult(String remoteUrl, int timeOut) {          
		String result = null;
        try {
	        URL url = new URL(remoteUrl);
	        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
	        conn.setConnectTimeout(timeOut);
	        conn.setRequestMethod("GET");
	        InputStreamReader  bis = new InputStreamReader(conn.getInputStream(),"utf-8");
	        BufferedReader br = new BufferedReader(bis);  
        	result = br.readLine();
        	br.close();
        	bis.close();
        	conn.disconnect();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return result;
} 
	public static String getVersionName(Context context){
		try {
			return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
		} catch (NameNotFoundException e) {
			return "1.0";
		}
	}
	
	public static String bytesToHexString(byte[] src) {      
        StringBuilder stringBuilder = new StringBuilder("0x");      
        if (src == null || src.length <= 0) {      
            return null;      
        }      
        char[] buffer = new char[2];      
        for (int i = 0; i < src.length; i++) {      
            buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);      
            buffer[1] = Character.forDigit(src[i] & 0x0F, 16);      
            System.out.println(buffer);      
            stringBuilder.append(buffer);      
        }      
        return stringBuilder.toString();      
    }
	
	public static Callback.Cancelable DonwloadFile(String url, File downloadFile, Callback.CommonCallback<File> callback) {
        RequestParams params = new RequestParams(url);
        params.setAutoRename(false);
        params.setAutoResume(true);
        params.setMaxRetryCount(3);
        params.setCancelFast(true);
        params.setSaveFilePath(downloadFile.getAbsolutePath());
        Callback.Cancelable cancelable = x.http().get(params, callback);
        return cancelable;
    }
	
	public static String getExtensionName(String filename) {    
        if ((filename != null) && (filename.length() > 0)) {    
            int dot = filename.lastIndexOf('.');    
            if ((dot >-1) && (dot < (filename.length() - 1))) {    
                return filename.substring(dot + 1);    
            }    
        }    
        return filename;    
    }   
	
	public static String getLocalIpAddress()  
    {  
		String hostIp = null;  
	    try {  
	        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();  
	        InetAddress ia = null;  
	        while (nis.hasMoreElements()) {  
	            NetworkInterface ni = (NetworkInterface) nis.nextElement();  
	            Enumeration<InetAddress> ias = ni.getInetAddresses();  
	            while (ias.hasMoreElements()) {  
	                ia = ias.nextElement();  
	                if (ia instanceof Inet6Address) {  
	                    continue;// skip ipv6  
	                }  
	                String ip = ia.getHostAddress();  
	                if (!"127.0.0.1".equals(ip)) {  
	                    hostIp = ia.getHostAddress();  
	                    break;  
	                }  
	            }  
	        }  
	    } catch (SocketException e) {  
	        e.printStackTrace();  
	    }  
	    return hostIp;  
    }  
	
	
	/**   
	 * @author: HYM 
	 * @Title: SbToString   
	 * @Description: TODO(StringBuilder 转化成 string 并去掉末尾的, )   
	 * @param sb
	 * @return String 
	 * @date: 2017-8-11
	 */  
	public static String SbToString(StringBuilder sb)
	{
		String list = sb.toString();
		if (list.endsWith(",")) {
			list = list.substring(0, list.length()-1);
		}
		Log.e("list ", list);
		return list;
	}
	
	public static boolean checkActivityIsNotExist(Context context)
	{
		if(context == null)
		{
			return true;
		}
		return false;
	}
}
